package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取所有分类及其子分类信息
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 获取所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 获取一级分类
        List<CategoryEntity> list = categoryEntities.stream().filter((categoryEntity -> categoryEntity.getParentCid() == 0))
        // 将获取到的一级分类进行子菜单属性赋值
        .map((menu)->{
            menu.setChildren(getChildrenInfo(menu,categoryEntities));
            return menu;
        })
        // 给树形数据进行排序操作
        .sorted((menu1,menu2) -> {
          return  (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        })
        .collect(Collectors.toList());
        // 获取分类下的子分类信息
        return list;
    }

    /**
     * 获取当前分类id下的父路径信息
     * @param catelogId
     * @return
     */
    @Override
    public Long[] getCatelogPath(Long catelogId) {
        // 创建保存父路径信息的数组
        List<Long> parentPath = new ArrayList<>();
        // 判断当前分类是否存在父分类信息,递归查找
        List<Long> returnParentPath = getParentPath(catelogId, parentPath);
        Collections.reverse(returnParentPath);
        Long[] array = returnParentPath.stream().toArray(Long[]::new);
        return array;
    }

    @Transactional //开启事务
    @Override
    public void updateCategory(CategoryEntity category) {
        // 更新自己,再更新关联表
        this.updateById(category);

        // 更新关联表
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    public List<Long> getParentPath(Long catelogId,List<Long> parentPath){
        // 获取当前分类信息
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity != null){
            // 将当前分类id保存
            parentPath.add(categoryEntity.getCatId());
            // 判断当前分类是否包含父分类信息id
            if (categoryEntity.getParentCid() != null){
                getParentPath(categoryEntity.getParentCid(),parentPath);
            }
        }

        return parentPath;
    }

    /**
     * 递归获取当前分类下的所有子分类信息
     * @param current
     * @param all
     * @return
     */
    public List<CategoryEntity> getChildrenInfo(CategoryEntity current,List<CategoryEntity> all){
        List<CategoryEntity> list = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == current.getCatId())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrenInfo(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((categoryEntity1, categoryEntity2) -> {
                    return  (categoryEntity1.getSort() == null ? 0 : categoryEntity1.getSort()) - (categoryEntity2.getSort() == null ? 0 : categoryEntity2.getSort());
                })
                .collect(Collectors.toList());
        return list;
    }
}